import axios from "axios";
import { message } from "ant-design-vue";
import { ResultData } from "./interface";

const service = axios.create({
  // baseURL: import.meta.env.VITE_BASE_API,
  timeout: 6000
});

// 添加请求拦截器
service.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    return config;
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加请求拦截器
service.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 添加响应拦截
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code === 200) {
      return Promise.resolve(res);
    } else {
      message.error(res.msg);
      return Promise.reject(res);
    }
  },
  error => {
    console.error(error);
    const errmsg = error.response.data.msg;
    if (errmsg) {
      message.error(errmsg);
    } else {
      message.error("系统内部错误！");
    }
    return Promise.reject(error.response);
  }
);

class Request {
  // get请求
  get<T>(url: string, params?: object, config?: object): Promise<ResultData<T>> {
    return service.get(url, {
      params,
      ...config
    });
  }
  // post请求
  post<T>(url: string, params?: object, config?: object): Promise<ResultData<T>> {
    return service.post(url, params, config);
  }
}

export default new Request();
